package com.sky.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dos.EmployeeDO;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.exception.*;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.pojo.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeByIdVO;
import com.sky.vo.EmployeeLoginVO;
import com.sky.vo.EmployeeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl  implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtProperties jwtProperties;


    //  编辑员工
    @Transactional
    @Override
    public void editEmpById(EmployeeDTO employeeDTO) {
        BeanUtil.hasNullField(employeeDTO,"password","status","updateTime","updateUser","createTime","createUser");
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        // 更新时间、更新人--使用aop代替
        /*employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());*/
        employeeMapper.updateEmpById(employee);
    }

    @Override
    public Result<EmployeeByIdVO> getEmpById(Long id) {
        if (Objects.isNull(id)){
            throw new ParameterIsNullException("员工ID不能为空");
        }
        EmployeeDO employeeDO = employeeMapper.getEmpById(id);
        EmployeeByIdVO vo = new EmployeeByIdVO();
        BeanUtils.copyProperties(employeeDO,vo);
        return Result.success(vo);
    }

    // 启用禁用员工
    @Transactional
    @Override
    public void startOrStop( Integer status,long id) {
        if (Objects.isNull(id) || Objects.isNull(status)){
            throw new ParameterIsNullException("员工状态和ID都不能为空");
        }
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.updateStatusById(employee);
    }

    // 员工分页查询
    @Override
    public PageResult<EmployeeVO> empListByPage(EmployeePageQueryDTO employeePageQueryDTO) {
        //  参数校验
        int empPage = employeePageQueryDTO.getPage();
        int empPageSize = employeePageQueryDTO.getPageSize();
        if (empPage <= 0 || empPageSize <= 0){
            throw new ParamsIllegalException("分页参数非法");
        }
        // 分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<EmployeeDO> page = employeeMapper.SelectPageQuery(employeePageQueryDTO);
        PageResult<EmployeeVO> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        List<EmployeeVO> recordList = page.getResult().stream().map(dos -> {
            EmployeeVO employeeVO = new EmployeeVO();
            BeanUtils.copyProperties(dos, employeeVO);
            return employeeVO;
        }).collect(Collectors.toList());
        pageResult.setRecords(recordList);
        return pageResult;
    }

    // 新增员工
    @Transactional
    @Override
    public Result<String> addEmp(EmployeeDTO employeeDTO) {
        // 参数校验
        BeanUtil.hasNullField(employeeDTO,"id");

        // 处理业务逻辑
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        // 判断用户名是否存在
        Employee byUsername = employeeMapper.getByUsername(employee.getUsername());
        if (Objects.nonNull(byUsername)){
            throw new EmployeeNameExistException(byUsername.getUsername()+"用户名已经存在:请重新输入");
        }

        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(StatusConstant.ENABLE);
        // 从ThreadLocal中获取当前登录用户的ID -使用aop代替
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());*/
        // 插入数据
        employeeMapper.insert(employee);
        // 封装数据
        return Result.success();
    }
    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Result<EmployeeLoginVO> login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();//

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw new ParameterIsNullException("用户名密码不能为空");
        }

        //1、根据用户名查询数据库中的数据  select * from employee where username = #{username}
        Employee employee = employeeMapper.getByUsername(username); //

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        // 在使用equals进行比较时，尽量把常量写在前面，请使用String类的equals方法进行比较，不要使用==
        if (StatusConstant.DISABLE.equals(employee.getStatus())) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }


        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        //3、返回实体对象
        return Result.success(employeeLoginVO);
    }




}
